package com.datastructures2.链表;

/**
 * @author MaoLin Wang
 * @date 2020/3/1616:14
 */
public class LinkedListDemo {
    public static void main(String[] args) {
        LinkedList la=new LinkedList();
        la.addNode(new Node(1));
        la.addNode(new Node(2));
        la.addNode(new Node(3));
        la.addNode(new Node(4));

        LinkedList lb=new LinkedList();
        lb.addNode(new Node(5));
        lb.addNode(new Node(6));
        lb.addNode(new Node(7));
        lb.addNode(new Node(8));


        LinkedList mergedList = mergeList(la,lb);
        System.out.println(mergedList);

    }


    /**
     * 当前链表和lb合并
     * @param lb
     * @return
     */
    public  static LinkedList mergeList(LinkedList la,LinkedList lb){
        ///这里head为链表的头节点，没有值 即 head-> 1-> 2 ->3 ->4  1开始才是链表的数据值
        //链表a为空
        if (la.head.next==null){
            //直接返回b
            return lb;
        }
        //链表b为空
        if (lb.head.next==null){
            //直接返回a
            return la;
        }
        //获取a的头节点
        Node head=la.head;
        //定义一个temp指针遍历链表a
        Node temp=head;
        //一个循环，让temp到达链表a的尾部
        while (temp.next!=null){
            temp=temp.next;
        }
        //此时temp已经在a的尾部，让a指向b的第一个节点
        temp.next=lb.head.next;
        return la;
    }
}
class LinkedList{
    Node head;

    public LinkedList() {
        this.head = new Node(null);
    }

    public Node getHead(){
        return head;
    }

    public void  addNode(Node node){
        Node temp=head;
        while (temp.next!=null){
            temp=temp.next;
        }
        temp.next=node;
    }

    @Override
    public String toString() {
        return "LinkedList{" +
                "head=" + head +
                '}';
    }
}
class Node{
    Object data;
    Node next;

    public Node(Object data) {
        this.data = data;

    }

    @Override
    public String toString() {
        return "Node{" +
                "data=" + data +
                ", next=" + next +
                '}';
    }
}